/**
 * 图片路由
 */
const express = require('express')
const multer = require("multer");
const path = require('path')
const {getBanners,getDisCountBanners,getHotGoodsBanners,saveSipper,saveHot,saveDiscount} = require("../utils/imageUtil.js")
const {openUrl,port} = require("../server.config.js")
const {log} = require('../utils/logger.js')
const {getImages,deleteImage} = require('../utils/fileUtil.js')
const fs = require('fs')

const imagesRounter = express.Router()

//图片加载,存储在images下的所有图片
imagesRounter.get(`/images/*`,async function (req, res) {
    res.sendFile( path.join(__dirname,'../',req.url));
    log("Request for " + req.url + " received.");
})

//获得所有轮播图的url地址
imagesRounter.get('/getSwippers',async function (req, res) {
    let data = await getBanners()
    data = JSON.parse(data)
    data.sort((x,y)=>{
        if(x.slot<y.slot)
            return -1
        else if(x.slot>y.slot){
            return 1
        }
        else
            return 0
    })
    data.forEach(element => {
        element.name = `http://${openUrl}:${port}/images/${element.name}`
    });
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/getSwippers`);
    res.send(data) 
})

//获得所有首页展示的特价商品
imagesRounter.get('/getDiscountsBanner',async function (req, res) {
    let data = await getDisCountBanners()
    data = JSON.parse(data)
    data.sort((x,y)=>{
        if(x.slot<y.slot)
            return -1
        else if(x.slot>y.slot){
            return 1
        }
        else
            return 0
    })
    data.forEach(element => {
        element.bannerName = `http://${openUrl}:${port}/images/${element.bannerName}`
    });
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/getDiscountsBanner`);
    res.send(data) 
})

//获得所有首页展示的特价商品
imagesRounter.get('/getHotGoodsBanner',async function (req, res) {
    let data = await getHotGoodsBanners()
    data = JSON.parse(data)
    data.sort((x,y)=>{
        if(x.slot<y.slot)
            return -1
        else if(x.slot>y.slot){
            return 1
        }
        else
            return 0
    })
    data.forEach(element => {
        element.bannerName = `http://${openUrl}:${port}/images/${element.bannerName}`
    });
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/getDiscountsBanner`);
    res.send(data) 
})

//保存轮播图信息
imagesRounter.post('/saveSwipper',async function (req, res) {
    let json = JSON.stringify(req.body)
    let ret = await saveSipper(json)
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/saveSwipper`);
    res.send(ret) 
})

//保存首页热销品
imagesRounter.post('/saveHot',async function (req, res) {
    let json = JSON.stringify(req.body)
    let ret = await saveHot(json)
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/saveHot`);
    res.send(ret) 
})
//保存首页折扣商品
imagesRounter.post('/saveDiscount',async function (req, res) {
    let json = JSON.stringify(req.body)
    let ret = await saveDiscount(json)
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/saveDiscount`);
    res.send(ret) 
})
/**
 * 获得所有的图片
 */
imagesRounter.get('/getImages',(req,res)=>{
    let ret = getImages()
    for(let i in ret){
        let item = ret[i]
        ret[i] = `http://${openUrl}:${port}/images/${item}`
    }
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/getImages`);

    res.send(ret)
})

/**
 * 通过文件名删除图片
 */
imagesRounter.post('/deleteImage/:name',(req,res)=>{
    res.send(deleteImage(req.params.name))
})


/**
 * 上传文件到服务器
 */

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // console.log(req.body) 
        //cb函数设置保存路径，__dirname为当前文件所在目录
        cb(null, path.join(__dirname,'../','images')) 
    },
    filename: function (req, file, cb) {
        file.originalname = Buffer.from(file.originalname, "latin1").toString(
            "utf8"
          );
        cb(null, file.originalname) 
    }
})

const upload = multer({storage:storage})
/**
 * 上传图片接口
 */
imagesRounter.post('/uploadImage',upload.single("image"),(req,res)=>{
    res.end('ok')
})
module.exports = imagesRounter